package com.agile.leetcode.order.orderid;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * 单机情况下可以，但是多台机器情况可能
 * @Author:ChenZhangKun
 * @Date: 2021/9/28 14:56
 */
public class GenerateOrderIdAtSingle {
    /**
     * 计数器
     */
    private static final AtomicInteger SEQUENCE = new AtomicInteger(1000);
    /**
     * 格式化时间
     * 保留两位毫秒数
     */
    private static final DateTimeFormatter DF_FMT_PREFIX = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSS");
    /**
     * 时区
     */
    private static ZoneId ZONE_ID = ZoneId.of("Asia/Shanghai");

    public static String generate() {
        // 当前时区的时间
        LocalDateTime localDateTime = LocalDateTime.now(ZONE_ID);
        if (SEQUENCE.intValue() > 9999) {
            SEQUENCE.getAndSet(1000);
        }
        return localDateTime.format(DF_FMT_PREFIX) + SEQUENCE.getAndIncrement();
    }

    public static void main(String[] args) {
        List<String> list = Collections.synchronizedList(new ArrayList<>());
        IntStream.range(0, 8000).parallel().forEach((i) -> {
            list.add(generate());
        });
        List<String> filterOrderNos = list.stream().distinct().collect(Collectors.toList());
        System.out.println("生成订单数= " + list.size());
        System.out.println("不重复订单数为= " + filterOrderNos.size());
        System.out.println("重复订单数为= " + (list.size() - filterOrderNos.size()));
    }
}
